import Vue from 'vue'
import router from '@/router'
import store from '@/store'

/**
 * 构建一个可以用方法式调用的对话框
 * @param promise
 * @param options
 * @returns {Promise<void>}
 */
export const buildDialog = async (promise, options = {}) => {
  const { listeners, props, data } = options
  const comp = await promise()

  const Dialog = Vue.extend({
    mixins: [comp.default],
    data() {
      const d = comp.default.data?.() || {}
      return { ...d, ...(data || {}) }
    }
  })

  const dialog = new Dialog({
    router,
    store,
    parent: router.app.$children[0],
    _parentListeners: { ...listeners, close },
    propsData: { ...(props || {}), visible: true }
  })

  function close() {
    listeners?.close?.()
    dialog.$destroy()
  }

  dialog.$on('close', close)

  if (listeners) {
    for (const eventName in listeners) {
      if (eventName !== 'close') {
        dialog.$on(eventName, listeners[eventName])
      }
    }
  }

  dialog.$mount()
}
